package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.exceptions.FeedLoaderException;

public class BankDataLoaderService {

	public static void getClientsFromFeed(Bank bank, File path) throws FeedLoaderException, IOException {

		try{
			Scanner fileScanner = new Scanner(path);
			while (fileScanner.hasNextLine() ){
				BankService.addClient(bank, getClientFromString( fileScanner.nextLine() ) );
			}
			fileScanner.close();
		} catch (FileNotFoundException e) {
			System.out.println( path.getAbsolutePath() + " is missing");
		}
	}

	public static Client getClientFromString(String str) throws FeedLoaderException{

		String[] correctKeys= {
			"accounttype", "balance", "overdraft", "name", "gender"};		

		String[] strArr = str.split(";");
		if (strArr.length != 5) throw new FeedLoaderException(
				"wrong number of parametrs - " + strArr.length + ". there must be 5 parameters");

		String[] clientValues = new String[5];
		
		for (int i=0; i < strArr.length; i++ ){

			Scanner sc = new Scanner(strArr[i]);
			sc.useDelimiter("=");
			String key = sc.next();
			String value = sc.next();
			sc.close();
			
			if (key.equals(correctKeys[i]) ){
				clientValues[i]=value;
			} else {
				throw new FeedLoaderException(
						"key '" + key + "' is incorrect");
			}
		}
				
		Account acc;
		double balance;
		double overdraft;
		
		try {
			balance = Double.parseDouble( clientValues[1] ); 
		} catch (NumberFormatException e) {
			throw new FeedLoaderException("incorrect value of balance " + clientValues[1] );
		}
				
		try {
			overdraft = Double.parseDouble( clientValues[2] );
		} catch (NumberFormatException e) {
			throw new FeedLoaderException("incorrect values of overdrft " + clientValues[2] );
		}

		if (clientValues[0].equals("c") ) {
			acc =  new CheckingAccount(balance, overdraft);
		} else if (clientValues[0].equals("s") ) {
			acc =  new SavingAccount(balance);
		} else {
			throw new FeedLoaderException("Incorrect account type - " + clientValues[0] );
		}
		
		String name = clientValues[3];
		
		Gender gen;
		if (clientValues[4].equals("m") ) {
			gen = Gender.MALE;
		} else if (clientValues[4].equals("f") ) {
			gen = Gender.FEMALE;
		} else {
			throw new FeedLoaderException("Incorrect gender - " + clientValues[4] );
		}
		
		return new Client(name, gen, acc);
	}
}